package com.lmx.api.controller;

import com.apiclient.pojo.LmApiClient;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.common.reflect.TypeToken;
import com.google.gson.Gson;
import com.lmx.api.annotation.AuthCheck;
import com.lmx.api.common.*;
import com.lmx.api.exception.BusinessException;
import com.lmx.api.model.dto.interfanceinfo.InterfanceInfoAddRequest;
import com.lmx.api.model.dto.interfanceinfo.InterfanceInfoQueryRequest;
import com.lmx.api.model.dto.interfanceinfo.InterfanceInfoUpdateRequest;
import com.lmx.api.model.dto.interfanceinfo.InterfanceInvokeRquest;
import com.lmx.api.until.ClientInvokeUntil;
import com.lmx.commen.model.entity.InterfanceInfo;
import com.lmx.commen.model.entity.User;
import com.lmx.api.service.InterfanceInfoService;
import com.lmx.api.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;

import static com.lmx.api.constant.UserConstant.USER_LOGIN_STATE;

/**
 * 帖子接口
 *
 * @author yupi
 */
@RestController
@RequestMapping("/interfanceinfo")
@Slf4j
public class InterfanceInfoController {

    @Resource
    private InterfanceInfoService interfanceInfoService;

    @Resource
    private UserService userService;
    @Resource
    private LmApiClient lmApiClient;

    /**
     * 创建
     *
     * @param interfanceInfoAddRequest
     * @param request
     * @return
     */
    @PostMapping("/add")
    public BaseResponse<Long> addPost(@RequestBody InterfanceInfoAddRequest interfanceInfoAddRequest, HttpServletRequest request) {
        if (interfanceInfoAddRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        InterfanceInfo interfanceinfo = new InterfanceInfo();
        BeanUtils.copyProperties(interfanceInfoAddRequest, interfanceinfo);
        // 校验
        interfanceInfoService.validInterfanceInfo(interfanceinfo, true);
        User loginUser = userService.getLoginUser(request);
        interfanceinfo.setUserid(loginUser.getId());
        boolean result = interfanceInfoService.save(interfanceinfo);
        if (!result) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR);
        }
        long newPostId = interfanceinfo.getId();
        return ResultUtils.success(newPostId);
    }

    /**
     * 删除
     *
     * @param deleteRequest
     * @param request
     * @return
     */
    @PostMapping("/delete")
    public BaseResponse<Boolean> deletePost(@RequestBody DeleteRequest deleteRequest, HttpServletRequest request) {
        if (deleteRequest == null || deleteRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User user = userService.getLoginUser(request);
        long id = deleteRequest.getId();
        // 判断是否存在
        InterfanceInfo oldInterfanceInfo = interfanceInfoService.getById(id);
        if (oldInterfanceInfo == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR);
        }
        // 仅本人或管理员可删除
        if (!oldInterfanceInfo.getUserid().equals(user.getId()) && !userService.isAdmin(request)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        boolean b = interfanceInfoService.removeById(id);
        return ResultUtils.success(b);
    }

    /**
     * 更新
     *
     * @param interfanceInfoUpdateRequest
     * @param request
     * @return
     */
    @PostMapping("/update")
    public BaseResponse<Boolean> updatePost(@RequestBody InterfanceInfoUpdateRequest interfanceInfoUpdateRequest,
                                            HttpServletRequest request) {

        if (interfanceInfoUpdateRequest == null || interfanceInfoUpdateRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        InterfanceInfo interfanceInfo = new InterfanceInfo();
        BeanUtils.copyProperties(interfanceInfoUpdateRequest, interfanceInfo);
        // 参数校验
        interfanceInfoService.validInterfanceInfo(interfanceInfo, false);
        User user = userService.getLoginUser(request);
        long id = interfanceInfo.getId();
        // 判断是否存在
        InterfanceInfo oldInterfanceInfo = interfanceInfoService.getById(id);
        if (oldInterfanceInfo == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR);
        }
        // 仅本人或管理员可修改
        if (!oldInterfanceInfo.getUserid().equals(user.getId()) && !userService.isAdmin(request)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        boolean result = interfanceInfoService.updateById(interfanceInfo);
        return ResultUtils.success(result);
    }


    /**
     * 根据 id 获取
     *
     * @param id
     * @return
     */
    @GetMapping("/get")
    public BaseResponse<InterfanceInfo> getPostById(long id) {
        if (id <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }

        InterfanceInfo interfanceInfo = interfanceInfoService.getById(id);
        return ResultUtils.success(interfanceInfo);
    }

    /**
     * 获取列表（仅管理员可使用）
     *
     * @param interfanceInfoQueryRequest
     * @return
     */
    @AuthCheck(mustRole = "admin")
    @PostMapping("/list")
    public BaseResponse<List<InterfanceInfo>> listPost(@RequestBody InterfanceInfoQueryRequest interfanceInfoQueryRequest) {
        InterfanceInfo interfanceInfoQuery = new InterfanceInfo();
        if (interfanceInfoQueryRequest != null) {
            BeanUtils.copyProperties(interfanceInfoQueryRequest, interfanceInfoQuery);
        }
        QueryWrapper<InterfanceInfo> queryWrapper = new QueryWrapper<>(interfanceInfoQuery);
        List<InterfanceInfo> interfanceInfoList = interfanceInfoService.list(queryWrapper);
        return ResultUtils.success(interfanceInfoList);
    }

    /**
     * 分页获取列表
     *
     * @param interfanceInfoQueryRequest
     * @param request
     * @return
     */
    @PostMapping("/list/page")
    public BaseResponse<IPage<InterfanceInfo>> listPostByPage(@RequestBody InterfanceInfoQueryRequest interfanceInfoQueryRequest, HttpServletRequest request) {


        if (interfanceInfoQueryRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        InterfanceInfo interfanceInfo = new InterfanceInfo();
        BeanUtils.copyProperties(interfanceInfoQueryRequest, interfanceInfo);
        String name = interfanceInfoQueryRequest.getName();
        String decprition = interfanceInfoQueryRequest.getDecprition();
        String url = interfanceInfoQueryRequest.getUrl();
        String method = interfanceInfoQueryRequest.getMethod();
        Integer status = interfanceInfoQueryRequest.getStatus();
        long current = interfanceInfoQueryRequest.getCurrent();
        long pageSize = interfanceInfoQueryRequest.getPageSize();


        // 限制爬虫
        if (pageSize > 50) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }

        LambdaQueryWrapper<InterfanceInfo> queryWrapper = new LambdaQueryWrapper<>();
        if (StringUtils.isNotEmpty(name)) {
            queryWrapper.like(InterfanceInfo::getName, name);
        }
        if (StringUtils.isNotEmpty(decprition)) {
            queryWrapper.like(InterfanceInfo::getDecprition, decprition);
        }
        if (StringUtils.isNotEmpty(method)) {
            queryWrapper.like(InterfanceInfo::getMethod, method);
        }
        if (StringUtils.isNotEmpty(url)) {
            queryWrapper.like(InterfanceInfo::getMethod, url);
        }

        if (status != null) {

            queryWrapper.eq(InterfanceInfo::getStatus, status);
        }

//        queryWrapper.like(InterfanceInfo::getStatus,status);
        IPage<InterfanceInfo> interfanceInfoPage = interfanceInfoService.page(new Page<>(current, pageSize), queryWrapper);
        return ResultUtils.success(interfanceInfoPage);
    }

    /**
     * 发布接口
     */
    @PostMapping("/online")
    public BaseResponse<Boolean> puhlishInterfance(@RequestBody UpdateRequest updateRequest, HttpServletRequest request) {
        if (updateRequest == null || updateRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User loginUser = (User) request.getSession().getAttribute(USER_LOGIN_STATE);

        if (loginUser == null) {
            throw new BusinessException(ErrorCode.NOT_LOGIN_ERROR);
        }

//        查看该接口是否存在
        InterfanceInfo updateInterfance = interfanceInfoService.getById(updateRequest.getId());
        if (updateInterfance == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
//        查看登录用户是接口创建者或管理员
        if (!updateInterfance.getUserid().equals(loginUser.getId()) && !userService.isAdmin(request)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
//        测试接口是否 可以调用
//        todo 现写死，后续需要根据用户接口调用不同的client方法
        com.apiclient.pojo.User clinetuser = new com.apiclient.pojo.User();
        clinetuser.setName("lmx");
        String nameTojSonBypost = lmApiClient.getNameTojSonBypost(clinetuser);
        if (StringUtils.isBlank(nameTojSonBypost)) {
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "接口调用失败");
        }

//        修改status为1
        InterfanceInfo interfanceInfo = new InterfanceInfo();
        interfanceInfo.setId(updateRequest.getId());
        interfanceInfo.setStatus(1);
        boolean b = interfanceInfoService.updateById(interfanceInfo);

//        返回true
        return ResultUtils.success(b);
    }

    @PostMapping("/offline")
    public BaseResponse<Boolean> offInterfance(@RequestBody UpdateRequest updateRequest, HttpServletRequest request) {
        if (updateRequest == null || updateRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User loginUser = (User) request.getSession().getAttribute(USER_LOGIN_STATE);

        if (loginUser == null) {
            throw new BusinessException(ErrorCode.NOT_LOGIN_ERROR);
        }

//        查看该接口是否存在
        InterfanceInfo updateInterfance = interfanceInfoService.getById(updateRequest.getId());
        if (updateInterfance == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
//        查看登录用户是接口创建者或管理员
        if (!updateInterfance.getUserid().equals(loginUser.getId()) && !userService.isAdmin(request)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }


//        修改status为1
        InterfanceInfo interfanceInfo = new InterfanceInfo();
        interfanceInfo.setId(updateRequest.getId());
        interfanceInfo.setStatus(0);
        boolean b = interfanceInfoService.updateById(interfanceInfo);

//        返回true
        return ResultUtils.success(b);
    }


    /**
     * 调用测试接口
     */

    @PostMapping("/invoke")
    public BaseResponse<Object> invodeInterfance(@RequestBody InterfanceInvokeRquest interfanceInvokeRquest, HttpServletRequest request) {
        log.info("/invoke{}",interfanceInvokeRquest.toString());
        if (interfanceInvokeRquest == null || interfanceInvokeRquest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User loginuser = (User) request.getSession().getAttribute(USER_LOGIN_STATE);

        if (loginuser == null) {
            throw new BusinessException(ErrorCode.NOT_LOGIN_ERROR);
        }
//        查询出接口的信息
        InterfanceInfo interfanceInfo = interfanceInfoService.getById(interfanceInvokeRquest.getId());
        if (interfanceInfo == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "接口不存在");
        }
        if (interfanceInfo.getStatus() != 1) {
            throw new BusinessException(ErrorCode.FORBIDDEN_ERROR, "接口未发布");
        }
        if (interfanceInvokeRquest.getParameters()==null){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"参数不能为空");
        }

        LmApiClient lmApiClient = new LmApiClient(loginuser.getAccessKey(), loginuser.getSecretKey());


//        Gson gson = new Gson();
//
//        Object pargmeter =gson.fromJson(interfanceInvokeRquest.getParameters(),
//                new TypeToken<Object>() {
//                }.getType());
        Object result = ClientInvokeUntil.invokeByhostAndApiAndMethod(
                loginuser.getAccessKey(),
                loginuser.getSecretKey(),
                interfanceInfo.getHost(),
                interfanceInfo.getUrl(),
                interfanceInfo.getMethod(), interfanceInvokeRquest.getParameters());
//        if (apiclientUser == null) {
//            throw new BusinessException(ErrorCode.PARAMS_ERROR, "请求参数不能为空");
//        }
//        String nameTojSonBypost = lmApiClient.getNameTojSonBypost(apiclientUser);

        return ResultUtils.success(result);


    }

}
